<?php

include dirname(dirname(dirname(__FILE__))) . '/include/common.php';

class webServiceLoginFacebook extends core {

    public function process() {
        /* CHECK EMAIL */

        if (!isset($_POST['email'])) {
            $this->_JSONResponse(array('error' => 1, 'msg' => 'Please enter email'));
        }

        $email = $this->_cleanEmail($_POST['email']);

        if (!$email) {

            $this->_JSONResponse(array('error' => 1, 'msg' => 'Please enter email'));
        }
        if (isset($_POST['pushtoken'])) {
            $device_token = trim($_POST['pushtoken']);
            $token_type = 'pushtoken';
        } else if (isset($_POST['udid'])) {
            $device_token = trim($_POST['udid']);
            $token_type = 'udid';
        } else {
            $this->_JSONResponse(array('error' => 1, 'msg' => 'Oops, something went wrong. Please try again'));
        }

        if (!$device_token) {

            $this->_JSONResponse(array('error' => 1, 'msg' => 'Oops, something went wrong. Please try again'));
        }

        $user = $this->db->get_row("SELECT * FROM users WHERE email LIKE '{$this->db->escape($email)}' LIMIT 1");
        $user_id = 0;
        $is_the_first_login_facebook = true;
        if (!$user) {
            $is_the_first_login_facebook = true;
            $data = array();
            $data['first_name'] = trim($_POST['firstname']);
            $data['last_name'] = trim($_POST['lastname']);
            $data['email'] = $this->_cleanEmail($_POST['email']);
            $data['password'] = "";
            $data['user_role'] = 2;
            $data['fiance_first_name'] = "";
            $data['fiance_last_name'] = "";
            $wedding_date = date('Y-m-d', time());
            $data['wedding_date'] = $wedding_date;
            $email = $this->db->escape($data['email']);
            $data['login_count'] = 0;
            $data['active'] = 1;
            $data['confirmation_code'] = "";
            $data['notification'] = 0;
            $data['facebook_id'] = intval($_POST['facebook_id']);
            $data['token'] = uniqid('', true);
            $fields = array();
            $values = array();
            $this->_preDataForInsert($data, $fields, $values);
            $fields = implode(',', $fields);
            $values = implode(',', $values);

            if (!$this->db->query("INSERT INTO `users` ({$fields}) VALUES ({$values});")) {

                $this->_JSONResponse(array('error' => 1, 'msg' => 'Oops, something went wrong. Please try again'));
            } else {
                $user_id = mysql_insert_id();
                $token = $data['token'];
                $firstName = $data['first_name'];
                $lastName =  $data['last_name']  ;                
                $userRole = 2;
                $query = "INSERT INTO `events` (`title`,`description`,`location`,`start_date`,`start_time`,`end_time`,`canbedeleted`,`user_id`)
                      VALUES ('Wedding','','','$wedding_date','','',0,$user_id);";
                
                $this->db->query($query);
            }
        } else {
            if ($user->facebook_id) {
                $is_the_first_login_facebook = false;
            }else{
                $is_the_first_login_facebook = true;
                $face_id = intval($_POST['facebook_id']);
                $this->db->query("UPDATE `users` SET `facebook_id` = {$face_id} WHERE id = '{$user->id}'");
            }
            //user is exist
            $user_id = $user->id;
            $token = $user->token;
            $firstName = $user->first_name;
            $lastName =  $user->last_name  ;                
            $userRole = $user->user_role;
            
        }
        //update table device & user_device if user login by new device
        //check table devices
        $device = $this->db->get_row("SELECT * FROM devices WHERE device_token LIKE '{$this->db->escape($device_token)}' LIMIT 1");
        $insert_profile = false;
        if (!$device) {
            $fields = array();
            $values = array();

            $this->_preDataForInsert(
                    array(
                'device_token' => $device_token,
                'token_type' => $token_type
                    ), $fields, $values);
            $fields = implode(',', $fields);
            $values = implode(',', $values);
            if (!$this->db->query("INSERT INTO `devices` ({$fields}) VALUES ({$values});")) {
                
                $this->_JSONResponse(array('error' => 1, 'msg' => 'Oops, something went wrong. Please try again'));
            }
            $device_id = $this->db->insert_id;
            $insert_profile = true;
        } else {
            $device_id = $device->device_id;
        }
        $profile_id=0;
        //check table user_device
        if (!$insert_profile) {
            $profile = $this->db->get_row("SELECT * FROM user_device WHERE device_id = '{$device_id}' AND `user_id` = '{$user_id}' LIMIT 1");
           
            if ($profile) {
                $profile_id = $profile->profile_id;
                
            }else{
                 $insert_profile = true;
            }
        }
        if($insert_profile) {

            $fields = array();
            $values = array();

            $this->_preDataForInsert(
                    array(
                'device_id' => $device_id,
                'user_id' => $user_id,
                'online' => 1
                    ), $fields, $values);

            $fields = implode(',', $fields);
            $values = implode(',', $values);

            if (!$this->db->query("INSERT INTO `user_device` ({$fields}) VALUES ({$values});")) {
                $this->_JSONResponse(array('error' => 1, 'msg' => 'Oops, something went wrong. Please try again'));
            }

            $profile_id = $this->db->insert_id;
            
        }else{
            $this->db->query("UPDATE `user_device` SET `online` = 0 WHERE device_id = '{$device_id}'");
            $this->db->query("UPDATE `user_device` SET `online` = 1 WHERE profile_id = '{$profile_id}' LIMIT 1;");
        }
        $this->_JSONResponse(array('error' => 0, 'profileID' => $profile_id,'userID'=> $user_id,'email'=>$email,'token'=>$token,'firstName'=>$firstName,'lastName'=>$lastName,'userRole'=>$userRole,'is_the_first_login_facebook'=>$is_the_first_login_facebook));
    }

}

$processor = new webServiceLoginFacebook();
$processor->process();
?>